package org.example.jdbc.bank.biz;

import org.example.jdbc.bank.bean.Account;
import org.example.jdbc.bank.bean.Record;
import org.example.jdbc.bank.dao.AccountDao;
import org.example.jdbc.bank.dao.RecordDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/4/23
 * Email haijunzhou@hnit.edu.cn
 */
@Service
// 加在类上,表示该类所有方法开启注解
// 默认请情况下, spring 只会对运行时异常回滚  runtimeException
@Transactional(rollbackFor = BizException.class,
        noRollbackFor = NullPointerException.class)
public class BankBizImpl implements BankBiz{

    @Resource
    AccountDao accountDao;
    @Resource
    RecordDao recordDao;


    @Override
    public void register(Account account) {
        accountDao.insert(account);
        Record record = new Record();
        record.setAid(account.getId());
        record.setOpmoney(account.getMoney());
        recordDao.insert(record);
    }

    @Override
    public void deposit(Integer id, double money) throws BizException {
        Account account = accountDao.selectById(id);
        account.setMoney(account.getMoney() + money);
        // 运行时异常, 在运行时才能感知,
        accountDao.update(account);
        // int i = 1/0;
        if(account.getMoney()> 1000000){
            throw new BizException("存款不能大于10000");
        }
        Object o = null;
        System.out.println(o.toString());
        Record record = new Record();
        record.setAid(account.getId());
        record.setOpmoney(money);
        recordDao.insert(record);
    }

    @Override
    public void withdraw(Integer id, double money) throws BizException {

        Account account = accountDao.selectById(id);
        if(money > account.getMoney()){
            throw new BizException("余额不足!");
        }
        account.setMoney(account.getMoney() - money);
        accountDao.update(account);
        Record record = new Record();
        record.setAid(account.getId());
        record.setOpmoney(-money);
        recordDao.insert(record);

    }

    @Override
    public void transfer(Integer id1, Integer id2, double money) throws BizException {
        this.withdraw(id1,money);
        this.deposit(id2,money);
    }

    // 加在方法上, 只对该方法有效
    @Transactional(readOnly = true)
    @Override
    public List<Record> query(Integer id) {
        return recordDao.selectByAccountId(id);
    }
}
